package com.mediacloud.app.newsmodule.fragment


import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.bumptech.glide.request.RequestOptions
import com.flyco.tablayout.SlidingTabLayout
import com.flyco.tablayout.listener.OnTabSelectListener
import com.mediacloud.app.adapter.ComponentRecyclerAdapter
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.assembly.util.isFastClick
import com.mediacloud.app.assembly.util.load
import com.mediacloud.app.fbnavsk.SecondNav
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.component.ComponentItem
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.component.ComponentListItemStyleAdaptor
import com.mediacloud.app.newsmodule.utils.NewsListDataInvoker
import com.mediacloud.app.newsmodule.utils.load
import com.mediacloud.app.newsmodule.utils.readData
import com.mediacloud.app.newsmodule.utils.saveData
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.appcloud.project.gxapp.model.utils.MD5Util
import com.scwang.smartrefresh.layout.api.RefreshFooter
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener
import com.zimeiti.activity.MConsecutiveViewPager
import com.zimeiti.activity.TabListFragment
import com.zimeiti.activity.TabWaterfallFragment
import kotlinx.android.synthetic.main.component_type89.*
import kotlinx.android.synthetic.main.fragment_blank_page.*
import org.json.JSONArray
import org.json.JSONException


/**
 * 强军号
 */
class NewBlankPageFragmentBack : HqyNavFragment(), OnRefreshLoadMoreListener,
    DataInvokeCallBack<ArticleListData>, ToolBarActionF5OrTop, Runnable {

    val titles: MutableList<String> = ArrayList()
    var catalogs: MutableList<CatalogItem> = ArrayList()
    val fragments: MutableList<Fragment> = ArrayList()
    var adapter: PagerAdapter? = null
    var catalogID: String? = null
    var componentAdapter: ComponentListItemStyleAdaptor? = null
    var catalogItem: CatalogItem? = null
    var dataInvoker: NewsListDataInvoker? = null
    var tabComponentItem: ComponentItem? = null
    var c89Item: ComponentItem? = null
    var c89ContentItem: MutableList<ComponentItem>? = null

    var mConsecutiveViewPager: MConsecutiveViewPager? = null
    var adapterComponent: ComponentRecyclerAdapter<ComponentItem>? = null


    override fun getLayoutResID(): Int {
        return R.layout.fragment_blank_page
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        navPaddingTopMatch()
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments!!.getString("id")
            catalogItem = saveInstanceArguments!!.getParcelable("catalog")
        }
        componentAdapter = ComponentListItemStyleAdaptor(requireContext(), catalogItem)
        refreshLayout.setEnableLoadMore(false)
        dataInvoker = NewsListDataInvoker(this)
        refreshLayout.setOnMultiPurposeListener(object : SimpleMultiPurposeListener() {
            override fun onFooterMoving(
                footer: RefreshFooter,
                isDragging: Boolean,
                percent: Float,
                offset: Int,
                footerHeight: Int,
                maxDragHeight: Int
            ) {
                scroller.stickyOffset = offset
            }
        })


//        refreshLayout.setRefreshFooter(BasicStyleFooter(requireContext()))

        /* if (isXXJT) {
             refreshLayout.setRefreshHeader(BasicStyleHeader(requireContext(), true))
             bgView.visibility = View.VISIBLE
 //            refreshLayout.setHeaderTextColor(Color.WHITE)
         } else {
             refreshLayout.setRefreshHeader(BasicStyleHeader(requireContext(), false))
             bgView.visibility = View.GONE
         }*/

    }

    var isFirstLoadingData = true
    override fun choosed() {
        super.choosed()
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed || isDetached || isRemoving) {
            return
        }
        initToRefresh()
    }

    override fun onResume() {
        super.onResume()
    }

    override fun initToRefresh() {
        if (isDetached || isRemoving) {
            return
        }
        if (isFirstLoadingData) {
            val dataResult = this.readData("$catalogID", ArticleListData::class.java)
            if (dataResult != null && (dataResult.articleList.size > 0 || dataResult.componentItems.size > 0)) {
                success(dataResult)
            } else {
                getData()
            }
            isFirstLoadingData = false
        }

    }

    private fun getData() {
        dataInvoker?.getContentList(catalogID, 1, 1, null)
    }

    var oldVerticalOffset: Int = 0
    override fun initView() {
        loadingView = findViewById(R.id.mLoadingView);
        initStateView();
        retryTips?.setOnClickListener {
            if (currentState != TYPE_LOADING) {
                showStateView(TYPE_LOADING, false)
                onRefresh(refreshLayout)
            }
        }
        showStateView(TYPE_LOADING, false)
        refreshLayout.setOnRefreshLoadMoreListener(this)

//        scroller.setOnVerticalScrollChangeListener { v, scrollY, oldScrollY, scrollState ->
////            Log.w("APPTAG","setOnVerticalScrollChangeListener---scrollY:${scrollY}---oldScrollY:${oldScrollY}")
//            if (scrollY == oldVerticalOffset && oldVerticalOffset != 0) {
//                return@setOnVerticalScrollChangeListener
//            }
//            if (scrollY > oldVerticalOffset) {
//                if (scrollY >= 20 && !isLocalOtherScrolled) {
//                    if (parentFragment is SecondNav) {
//                        (parentFragment as SecondNav).scrollHqyToolbar(ScrollDirection(1, scrollY))
//                    } else if (parentFragment is HammerNavigateSub) {
//                        if ((parentFragment as HammerNavigateSub) is SecondNav) {
//                            ((parentFragment as HammerNavigateSub) as SecondNav).scrollHqyToolbar(
//                                ScrollDirection(1, scrollY)
//                            )
//                        }
//                    }
//                    isLocalOtherScrolled = true
//                    scroller.stickyOffset = scrollY
//                }
//
//            }
//            if (oldVerticalOffset > scrollY) {
//                // 向下滑动
//                if (scrollY >= 20 && isLocalOtherScrolled) {
//                    if (parentFragment is SecondNav) {
//                        (parentFragment as SecondNav).scrollHqyToolbar(ScrollDirection(2, scrollY))
//                    } else if (parentFragment is HammerNavigateSub) {
//                        if ((parentFragment as HammerNavigateSub) is SecondNav) {
//                            ((parentFragment as HammerNavigateSub) as SecondNav).scrollHqyToolbar(
//                                ScrollDirection(2, scrollY)
//                            )
//                        }
//                    }
//                    isLocalOtherScrolled = false
//                    scroller.stickyOffset = 0
//                }
//
//            }
//            oldVerticalOffset = scrollY
//        }
        if (parentFragment is SecondNav) {
            if (isAdded && hadChoosed) {

                initToRefresh()
            }
        } else {
            if (isAdded) {
                initToRefresh()
            }
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        getData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mConsecutiveViewPager?.let {
            val index = it.currentItem
            val f = fragments[index]
            if (f is OnLoadMoreListener) {
                f.onLoadMore(refreshLayout)
            }
        }

    }


    val views: MutableList<View> = ArrayList()
    val tempViews: MutableList<View> = ArrayList()

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun success(data: ArticleListData?) {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
            return
        }
        //不是上次的缓存数据才进行缓存
        val isCacheData = data?.orginData?.optInt("is_cache", 0) == 1
        if (!isCacheData) {
            try {
                data?.orginData?.put("is_cache", 1)
                saveData("$catalogID", data?.orginData.toString() + "")
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
        refreshLayout.finishRefresh()
        if (data?.state == true) {
            scroller.removeCallbacks(this)
            scroller.removeAllViews()
            views.clear()
            tempViews.clear()
            tabComponentItem = null
            componentAdapter?.clearEvent()
            val componentList = data.componentItems
            val size = componentList.size
            componentAdapter?.listContentData = componentList

            for (index in 0 until size) {
                val item = componentList[index]
                if (item.widget == TypeX.COMPONENT_X.C999912 || item.widget == TypeX.COMPONENT_X.C999988) {
                    tabComponentItem = item
                    break
                }
                if (item.widget == TypeX.COMPONENT_X.C999989 || c89Item != null) {
                    if (c89Item == null) {
                        c89Item = item
                        c89ContentItem = ArrayList()
                    } else {
                        c89ContentItem?.add(item)
                    }
                } else {
                    val view = componentAdapter?.getView(index, null, null) ?: continue
                    views.add(view)
                }
            }

            val count = if (views.size > 4) {
                4
            } else {
                views.size
            }

            for (i in 0 until count) {
                val v = views[i]
                tempViews.add(v)
                scroller.addView(v, -1, -2)
            }
            views.removeAll(tempViews)
            if (views.size > 0) {
                if (isCacheData) {
                    onRefresh(refreshLayout)
                }else{
                    scroller.postDelayed(this, 800)
                }
            } else {
                if (isCacheData) {
                    onRefresh(refreshLayout)
                } else {
                    c89Item?.let {
                        setComponent89(it, c89ContentItem!!)
                    }
                    tabComponentItem?.let {
                        buildTab(it)
                    }
                    if (tabComponentItem == null) {
                        refreshLayout.finishLoadMoreWithNoMoreData()
                    }
                }
            }

        }
        closeStateView()

    }


    override fun run() {
        for (i in 0 until views.size) {
            val v = views[i]
            tempViews.add(v)
            scroller.addView(v, -1, -2)
        }
        c89Item?.let {
            setComponent89(it, c89ContentItem!!)
        }
        tabComponentItem?.let {
            buildTab(it)
        }
        if (tabComponentItem == null) {
            refreshLayout.finishLoadMoreWithNoMoreData()
        }
    }

    override fun fault(data: Any?) {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
            return
        }
        refreshLayout.finishRefresh(false)
        refreshLayout.setEnableLoadMore(false)
        closeStateView()
    }


    private fun buildTab(componentItem: ComponentItem) {
        refreshLayout?.setEnableLoadMore(true)
        titles.clear()
        catalogs.clear()
        fragments.clear()
//        val layoutId = if (componentItem.widget == TypeX.COMPONENT_X.C999988){
//            R.layout.item_componentt_tab2
//        }else{
//            R.layout.item_componentt_tab
//        }
        //都不要吸顶  http://devops.test.chinamcloud.com/project/129/issue#statusId=28+30&assignedToIds=73255&filterType=Basic&type=Bug&openTaskId=10946
        val layoutId = R.layout.item_component_tab
        val view = LayoutInflater.from(requireContext()).inflate(layoutId, scroller, true)
        val tabImage: ImageView = view.findViewById(R.id.tabImage)
        val tabContainer: View = view.findViewById(R.id.tabContainer)
        val tabLayout: SlidingTabLayout = view.findViewById(R.id.tabLayout)

        mConsecutiveViewPager = view.findViewById(R.id.mConsecutiveViewPager)

        val tabImageLp = tabImage.layoutParams as ViewGroup.MarginLayoutParams
        tabImageLp.height = resources.getDimensionPixelSize(R.dimen.dimen40)
        tabContainer.setBackgroundColor(Color.WHITE)
        var fontSize = 20
        var width_as_screen = false
        try {
            val other_field = componentItem.orginDataObject.optJSONObject("other_field")
            val font_default_color = other_field.optString("font_default_color")
            val font_selected_color = other_field.optString("font_selected_color")
            val selected_color = Color.parseColor(font_selected_color)
            tabLayout.textUnselectColor = Color.parseColor(font_default_color)
            tabLayout.textSelectColor = selected_color
            val is_selected_underline = other_field.optInt("is_selected_underline")

            val font_default_size = other_field.optInt("font_default_size", 20)
            val font_selected_size = other_field.optInt("font_selected_size", 20)
            fontSize = font_selected_size
            tabLayout.textsize = font_default_size.toFloat()
            if (is_selected_underline == 0) {
                tabLayout.indicatorHeight = 0f
            } else {
                tabLayout.indicatorColor = selected_color
                tabLayout.indicatorHeight = 3f
            }

            tabLayout.setOnTabSelectListener(object : OnTabSelectListener {
                override fun onTabSelect(position: Int) {
                    for (i in 0 until tabLayout.getTabCount()) {
                        val textView: TextView = tabLayout.getTitleView(i)
                        if (position == i) {
                            textView.textSize = font_selected_size.toFloat()
                            textView.typeface = Typeface.DEFAULT_BOLD
                        } else {
                            textView.textSize = font_default_size.toFloat()
                            textView.typeface = Typeface.DEFAULT
                        }
                    }
                }

                override fun onTabReselect(position: Int) {}
            })



            if (componentItem.widget == TypeX.COMPONENT_X.C999912) {
                val bg_img = other_field.optString("bg_img")
                if (!TextUtils.isEmpty(bg_img)) {
                    val option =
                        RequestOptions().error(AppFactoryGlobalConfig.defaultImageLoadDrawable)
                    tabImage.load(bg_img, option)
                }

                width_as_screen = other_field.optString("width_as_screen") == "1"
                if (!width_as_screen) {
                    val margin = resources.getDimensionPixelSize(R.dimen.dimen12)
                    tabImageLp.marginStart = margin
                    tabImageLp.marginEnd = margin
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        if (componentItem.widget == TypeX.COMPONENT_X.C999912) {
            val w = Utility.getScreenWidth(requireContext())
            if (width_as_screen) {
                tabImageLp.width = w
                tabImageLp.height = w * componentItem.height / componentItem.width
            } else {
                tabImageLp.width = w - 2 * resources.getDimensionPixelSize(R.dimen.dimen12)
                tabImageLp.height = tabImageLp.width * componentItem.height / componentItem.width
            }
        }
        tabImage.layoutParams = tabImageLp


        val element = componentItem.getElement()
        try {
            val jsonArray = JSONArray(element)
            val length = jsonArray.length()

            for (i in 0 until length) {
                jsonArray.optJSONObject(i)?.let { element ->
                    val item = CatalogItem()
                    val name = element.optString("title", "")
                    item.catname = name
                    element.optJSONObject("navigate")?.let {
                        item.catid = it.optString("id")
                        item.catalog_type = it.optString("category")
                    }

                    titles.add(name)
                    catalogs.add(item)
                    if (componentItem.widget == TypeX.COMPONENT_X.C999988) {
                        fragments.add(TabWaterfallFragment.newInstance(item.catid, item/*, d*/))
                    } else {
                        fragments.add(TabListFragment.newInstance(item.catid, item/*, d*/))
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        mConsecutiveViewPager?.offscreenPageLimit = fragments.size
        adapter = PagerAdapter(fragments, titles, childFragmentManager)
        mConsecutiveViewPager?.adapter = adapter
        mConsecutiveViewPager?.setNoScroll(true)
        tabLayout.setViewPager(mConsecutiveViewPager)
        tabLayout.getTitleView(0).setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize.toFloat())
        tabLayout.getTitleView(0).typeface = Typeface.DEFAULT_BOLD
        mConsecutiveViewPager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                val f = fragments[position]
                if (f is TabListFragment) {
                    refreshLayout?.setNoMoreData(!f.hasMore)
                } else if (f is TabWaterfallFragment) {
                    refreshLayout?.setNoMoreData(!f.hasMore)
                }

            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })
        if (componentItem.widget == TypeX.COMPONENT_X.C999988) {
            mConsecutiveViewPager?.setNoScroll(false)
            if (titles.size <= 1) {
                tabContainer.visibility = View.GONE
            } else {
                tabContainer.visibility = View.VISIBLE
            }
        }
    }


    private fun setComponent89(
        componentItem: ComponentItem,
        contentList: MutableList<ComponentItem>
    ) {
        refreshLayout.setEnableLoadMore(false)
        val view =
            LayoutInflater.from(requireContext()).inflate(R.layout.component_type89, scroller, true)
        val girdView: GridView = view.findViewById(R.id.gridView)
        val tabContainer: FrameLayout = view.findViewById(R.id.tabContainer)
        val spanCount = componentItem.getCol()
        girdView.numColumns = spanCount
        val adapter = Adapter(requireContext())
        gridView.adapter = adapter


        adapterComponent = ComponentRecyclerAdapter(requireContext())
        adapterComponent?.catalogItem = catalogItem
        val recyclerView2: RecyclerView = view.findViewById(R.id.recyclerView2)
        val layoutManager = LinearLayoutManager(requireContext())
        recyclerView2.layoutManager = layoutManager
        recyclerView2.adapter = adapterComponent

        recyclerView2.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //获取RecyclerView当前顶部显示的第一个条目对应的索引
                val position = layoutManager.findFirstVisibleItemPosition()
                if (position != adapter.selectPosition) {
                    adapter.selectPosition = position
                    adapter.notifyDataSetChanged()
                }

            }
        })

        girdView.setOnItemClickListener { parent, view, position, id ->
            if (isFastClick()) {
                scroller.scrollToChild(tabContainer)
                adapter.selectPosition = position
                adapter.notifyDataSetChanged()
                layoutManager.scrollToPositionWithOffset(position, 0)
            }
        }
        componentItem.orginDataObject?.let {
            var ratio_x = 1
            var ratio_y = 1
            it.optJSONObject("other_field")?.let {
                ratio_x = it.optInt("ratio_x")
                ratio_y = it.optInt("ratio_y")
            }
            adapter.dimensionRatio = "W,${ratio_y}:${ratio_x}"
            val elements = it.optJSONArray("element")
            val size = elements.length()
            val list: MutableList<Item> = ArrayList();
            for (i in 0 until size) {
                elements.optJSONObject(i)?.let {
                    list.add(Item(it.optString("icon"), it.optString("icon_selected")))
                }
            }
            adapter.list.clear()
            adapter.list.addAll(list)
            adapter.notifyDataSetChanged()
        }


        adapterComponent?.data = contentList
        adapterComponent?.notifyItemRangeChanged(0, contentList.size)
    }

    override fun f5() {
//        scroller.scrollToChild(tabContainer)
//        scroller.postDelayed({
//            if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
//                return@postDelayed
//            }
//            scroller.scrollY = 0
//        }, 100)
        scroller.scrollToChild(scroller.getChildAt(0))
        refreshLayout.autoRefresh(300)
    }

    override fun gun() {
//        scroller.scrollToChild(tabContainer)
//        scroller.postDelayed({
//            if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
//                return@postDelayed
//            }
//            scroller.scrollY = 0
//        }, 100)
        scroller.scrollToChild(scroller.getChildAt(0))
    }

//
//    class Adapter(val context: Context) : BaseQuickAdapter<Item, BaseViewHolder>(R.layout.item_component89) {
//        var dimensionRatio = "W,9:16"
//        var selectPosition = 0
//        override fun convert(helper: BaseViewHolder, item: Item?) {
//            val logoIv: ImageView = helper.getView(R.id.logoIv)
//
//            if (selectPosition == helper.absoluteAdapterPosition) {
//                logoIv.load(item?.icon_selected, false, ColorDrawable(Color.WHITE))
//            } else {
//                logoIv.load(item?.icon, false, ColorDrawable(Color.WHITE))
//            }
//            val lp = logoIv.layoutParams as ConstraintLayout.LayoutParams
//            lp.dimensionRatio = dimensionRatio
//            logoIv.layoutParams = lp
//
//        }
//    }


    class Adapter(val context: Context) : BaseAdapter() {
        var dimensionRatio = "W,9:16"
        var selectPosition = 0
        val list: MutableList<Item> = ArrayList()
        override fun getCount(): Int {
            return list.size
        }

        override fun getItem(position: Int): Any {
            return list[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, _convertView: View?, parent: ViewGroup?): View {
            var holder: Holder? = null

            var convertView: View? = _convertView
            if (convertView == null) {
                convertView =
                    LayoutInflater.from(context).inflate(R.layout.item_component89, parent, false);
                holder = Holder()
                holder.logoIv = convertView?.findViewById(R.id.logoIv)
                convertView.tag = holder
            } else {
                holder = convertView.tag as Holder
            }
            val item = list[position]
            if (selectPosition == position) {
                holder.logoIv?.load(item.icon_selected, false, ColorDrawable(Color.WHITE))
            } else {
                holder.logoIv?.load(item.icon, false, ColorDrawable(Color.WHITE))
            }
            val lp = holder.logoIv?.layoutParams as ConstraintLayout.LayoutParams
            lp.dimensionRatio = dimensionRatio
            holder.logoIv?.layoutParams = lp
            return convertView!!
        }
    }

    class Holder {
        var logoIv: ImageView? = null
    }

    data class Item(val icon: String?, val icon_selected: String?)

    override fun onDestroyView() {
        fragments.clear()
        childFragmentManager.fragments.clear()
        adapterComponent?.destroy()
        componentAdapter?.clearEvent()
        mConsecutiveViewPager?.adapter = null
        mConsecutiveViewPager?.clearOnPageChangeListeners()
        dataInvoker?.destory()
        super.onDestroyView()
    }

}